package com.feng.controller.back;

import com.feng.vo.FileVo;
import com.feng.vo.ResultFileVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

/**
 * @author: 丰
 * @date: 2022/12/30 15:27
 */
@RestController
@RequestMapping("/back/file")
@Api(tags = "后台文件接口")
public class FileController {

    // 文件上传的文件夹
    private static final String UPLOAD_DIRECTORY = "upload";

    // @RequestParam("file") 指明当前参数来源于请求参数，key为file
    @ApiOperation("封面的文件上传（单文件）")
    @PostMapping("/upload")
    public ResultFileVo upload(@RequestParam("file") MultipartFile uploadFile, HttpServletRequest req){
        if(uploadFile == null) {
            System.out.println("null of upload file");
        } else {
            // 获取存储文件路径
            String realPath = req.getServletContext().getRealPath("./");// 项目根路径
            String uploadPath = realPath + "/" + UPLOAD_DIRECTORY;

            // 如果文件夹不存在，就创建
            File fileDir = new File(uploadPath);
            if (!fileDir.exists()){
                fileDir.mkdir();
            }
            // 获得上传的文件名
            String name = uploadFile.getOriginalFilename();
            // 防止同文件重名
            String fileName = System.currentTimeMillis() + "--" + name;
            // 拼接文件存储的绝对路径
            String filePath = uploadPath + "/" + fileName;
            File storeFile = new File(filePath);
            try {
                //保存文件
                uploadFile.transferTo(storeFile);
                // 将文件复制到当前工作目录下
                String path = storeFile.getPath().split("target")[0] + "/web/" + UPLOAD_DIRECTORY + "/";
                copyFile(filePath, path, fileName);
                // 相应前端，存储数据库
                ResultFileVo resultVo = ResultFileVo.success(new FileVo(fileName, "/" + UPLOAD_DIRECTORY + "/" + fileName));
                return resultVo;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return ResultFileVo.failed();
    }


    /**
     * 富文本的多文件上传
     * @return
     */
    @ApiOperation("富文本的文件上传（多文件）")
    @PostMapping("/upload2")
    public ResultFileVo upload2(@RequestParam("file") MultipartFile[] uploadFiles, HttpServletRequest req) {
        ResultFileVo resultFileVo = ResultFileVo.failed();
        if (uploadFiles != null){
            for (MultipartFile uploadFile : uploadFiles) {
                if(uploadFile == null) {
                    System.out.println("null of upload file");
                } else {
                    // 获取存储文件路径
                    String realPath = req.getServletContext().getRealPath("./");// 项目根路径
                    String uploadPath = realPath + "/" + UPLOAD_DIRECTORY;

                    // 如果文件夹不存在，就创建
                    File fileDir = new File(uploadPath);
                    if (!fileDir.exists()){
                        fileDir.mkdir();
                    }
                    // 获得上传的文件名
                    String name = uploadFile.getOriginalFilename();
                    // 防止同文件重名
                    String fileName = System.currentTimeMillis() + "--" + name;
                    // 拼接文件存储的绝对路径
                    String filePath = uploadPath + "/" + fileName;
                    File storeFile = new File(filePath);
                    try {
                        //保存文件
                        uploadFile.transferTo(storeFile);
                        // 将文件复制到当前工作目录下
                        String path = storeFile.getPath().split("target")[0] + "/web/" + UPLOAD_DIRECTORY + "/";
                        copyFile(filePath, path, fileName);
                        // 相应前端，存储数据库
                        resultFileVo = ResultFileVo.success(new FileVo(fileName, req.getContextPath() + "/" + UPLOAD_DIRECTORY + "/" + fileName)).code(0);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
        return resultFileVo;
    }


    /**
     * 拷贝文件
     * @param sourceFile 文件
     * @param targetPath 新路径地址
     * @param fileName 文件名称
     */
    private void copyFile(String sourceFile, String targetPath, String fileName) {

        File file1 = new File(targetPath);
        if (!file1.exists()){
            file1.mkdir();
        }
        File file = new File(sourceFile);
        try (InputStream inputStream = new FileInputStream(file);
             OutputStream outputStream = new FileOutputStream(file1 + "/" + fileName)) {
            int read = 0;
            while ((read = inputStream.read()) != -1) {
                outputStream.write(read);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
